//
//  LSZVideoPlaybackInterfaceVC.m
//  JKFuYinProject
//
//  Created by 九酷 on 2018/9/6.
//  Copyright © 2018年 LC. All rights reserved.
//

#import "LSZVideoPlaybackInterfaceVC.h"
#import "JDVideoModel.h"
#import "JDPlayerView.h"
#import "JDPlayer.h"


@interface LSZVideoPlaybackInterfaceVC ()<UINavigationControllerDelegate,JDPlayerDelegate,UITableViewDelegate,UITableViewDataSource,UIGestureRecognizerDelegate>

@property(nonatomic,strong) JDPlayer* player;
@property(nonatomic,strong) NSString * playUrl;
@property(nonatomic,strong) UITableView * tableViewList;
@property(nonatomic,strong) NSString * lyrics;
@property(nonatomic,strong) NSString * name;
@end

@implementation LSZVideoPlaybackInterfaceVC
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    // 设置导航控制器的代理为self
    self.navigationController.delegate = self;
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.player pauseContent];
    self.player = nil;
}
#pragma mark - 得到歌词
-(void)toGetTheLyrics
{
    [LSZRequestData initMVAcquisitionLyrics:self.lastMg.id_id :^(BOOL isOK, NSString * str, NSDictionary * dic) {
        if (isOK == YES) {
            self.name = dic[@"data"][@"name"];
            NSString * str = dic[@"data"][@"lyrics"];
            NSString * strLyrics = [dic[@"data"][@"lyrics"] stringByReplacingOccurrencesOfString:@"<br /><br />" withString:@"\r\n"];
            self.lyrics = [strLyrics stringByReplacingOccurrencesOfString:@"<br />" withString:@"\r\n"];
            [self.tableViewList reloadData];
        }else{
            [self initWithtring:str];
        }
    }];
    UIButton * butDedication = [[UIButton alloc]init];
    butDedication.frame = CGRectMake(0, ScreenHeight-50, ScreenWidth, 50);
    butDedication.backgroundColor = [UIColor blackColor];
    [butDedication setTitle:@"奉献支持" forState:UIControlStateNormal];
    butDedication.titleLabel.font = FONT_(16);
    [butDedication addTarget:self action:@selector(clickButDedication) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:butDedication];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self addObserver];
    [self toGetTheLyrics];
    [self.tableViewList registerClass:[LSZHeaderBasicInformationHeaderCell class] forCellReuseIdentifier:@"LSZHeaderBasicInformationHeaderCell"];
    [self playVideo];
    [self addNotificationCenter];
}
-(void)addNotificationCenter
{
    //返回键
    __weak typeof(self) weakSelf = self;
    weakSelf.player.jdView.doneButtonBlock = ^{
        [weakSelf.player pauseContent];
        [weakSelf.navigationController popViewControllerAnimated:YES];
    };
    weakSelf.player.parseFailureBlock = ^{
        [weakSelf initWithtring:@"解析失败!"];
        [weakSelf.player pauseContent];
    };
    weakSelf.player.jdView.playSuspendBlock = ^{
        NSLog(@"暂停");
        [weakSelf.player pauseContent];
    };
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(InfoNotificationSwitchScreen:) name:@"switchScreen" object:nil];//切换屏幕
}
#pragma mark - 首次播放的url
- (void)playVideo
{
    JDVideoModel* videoModel = [[JDVideoModel alloc]init];
    self.playUrl = [NSString stringWithFormat:@"%@?%@", self.lastMg.listen_url,[self usingRandomNumbers]];//使用随机数是可以
    videoModel.streamURL = [NSURL URLWithString:
                            [NSString stringWithFormat:@"?src=%@",[NSDate.new timeStampStr]]
                                  relativeToURL:[NSURL URLWithString:[self.playUrl codeString]]];
    [self.player loadVideoModel:videoModel];
}
-(NSString *)stringUrl :(NSString *)string
{
    NSString*playUrl = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    return playUrl;
}
#pragma mark - App States
- (void)applicationWillResignActive
{
    self.player.jdView.countdownToHide = -1;
    if (self.player.state == JDPlayerStatePlaying){
        [self.player pauseContent:NO recordCurrentTime:YES completionHandler:nil];
    }
}
- (void)applicationDidBecomeActive
{
    self.player.jdView.countdownToHide = -1;
}
#pragma mark - 所有的播放完毕 也会走这个方法
- (void)videoPlayer:(JDPlayer*)videoPlayer didPlayToEnd:(JDVideoModel *)videoModel
{
    [self.player pauseContent];
}
- (void)videoPlayer:(JDPlayer *)videoPlayer didNextVideoButtonPressed:(JDVideoModel *)videoModel
{
    NSLog(@"截屏");
    float currentTime = CMTimeGetSeconds([_player.avPlayer currentCMTime]) - 0.5f;
    NSLog(@"[_player.avPlayer currentCMTime] = %f", currentTime);

    NSURL *url = [NSURL URLWithString:
                  [NSString stringWithFormat:@"?src=%@",[NSDate.new timeStampStr]]
                        relativeToURL:[NSURL URLWithString:[self.playUrl codeString]]];
    AVAsset *asset = [AVAsset assetWithURL:url];
    AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    // 在苹果API中看到 Asynchronously 词汇需要注意回调函数的多线程
    @weakify(self)
    [SVProgressHUD showSuccessWithStatus:@"截屏成功!"];

    [generator generateCGImagesAsynchronouslyForTimes:@[@(currentTime)] completionHandler:^(CMTime requestedTime, CGImageRef  _Nullable image, CMTime actualTime, AVAssetImageGeneratorResult result, NSError * _Nullable error) {
        dispatch_sync(dispatch_get_main_queue(), ^{
            @strongify(self)
            UIImage *img = [UIImage imageWithCGImage:image];
            JKAlertView *alertView = [JKAlertView alertViewWithTitle:nil message:nil style:(JKAlertStyleActionSheet)];
            [alertView addAction:[JKAlertAction actionWithTitle:@"微信分享" style:(JKAlertActionStyleDefault) handler:^(JKAlertAction *action) {
                [self shareNoUIWithImageArray:@[img] url:nil title:@"九酷福音" contentMessage:@"九酷福音" type:(SSDKContentTypeImage) platformType:(SSDKPlatformSubTypeWechatSession)];
            }]];
            [alertView addAction:[JKAlertAction actionWithTitle:@"朋友圈分享" style:(JKAlertActionStyleDefault) handler:^(JKAlertAction *action) {
                [self shareNoUIWithImageArray:@[img] url:nil title:@"九酷福音" contentMessage:@"九酷福音" type:(SSDKContentTypeImage) platformType:(SSDKPlatformSubTypeWechatTimeline)];
            }]];
            alertView.enableDeallocLog(YES).show().setDismissComplete(^{
                [SVProgressHUD dismiss];
            });
        });
    }];
}
- (void)handleErrorCode:(JDPlayerErrorCode)errorCode track:(JDVideoModel *)track customMessage:(NSString*)customMessage
{
    NSLog(@"errorCode : %ld,message : %@ , url : %@",(long)errorCode,customMessage,track.streamURL);
}
- (JDPlayer *)player
{
    if(!_player){
        _player = [[JDPlayer alloc] init];
        _player.delegate = self;
        [self.view addSubview:_player.jdView];
        if (iPhoneX ) {
            _player.jdView.frame = CGRectMake(0, 0, self.view.frame.size.width,ScreenWidth*9/16+24);//进度条
        }else{
            _player.jdView.frame = CGRectMake(0, 0, self.view.frame.size.width,ScreenWidth*9/16);//进度条
        }
    }
    return _player;
}
- (BOOL)prefersStatusBarHidden
{
    return YES;
}
-(void)InfoNotificationSwitchScreen:(NSNotification *)notification
{
    NSDictionary * dic = notification.userInfo;
    NSString * screenStr = dic[@"screen"];
    if ([screenStr isEqualToString:@"1"]) {
        self.tableViewList.hidden = YES;
    }else{
        self.tableViewList.hidden = NO;
    }
}
- (void)addObserver
{
    NSNotificationCenter* defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(applicationWillResignActive) name:UIApplicationWillResignActiveNotification object:nil];
    [defaultCenter addObserver:self selector:@selector(applicationDidBecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil];
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    // 若为UITableViewCellContentView（即点击了tableViewCell），则不截获Touch事件
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]){
        return NO;
    }
    return  YES;
}
#pragma mark ________________ 目录列表______________________
-(UITableView *)tableViewList
{
    if (_tableViewList == nil) {
        _tableViewList = [[UITableView alloc]initWithFrame:CGRectMake(0,ScreenWidth*9/16, ScreenWidth, ScreenHeight-ScreenWidth*9/16-50) style:UITableViewStyleGrouped];
        if (iPhoneX) {
            _tableViewList.frame = CGRectMake(0,ScreenWidth*9/16+24, ScreenWidth, ScreenHeight-ScreenWidth*9/16-24-50);
        }
        _tableViewList.dataSource =self;
        _tableViewList.delegate = self;
        _tableViewList.estimatedRowHeight=0;
        _tableViewList.estimatedSectionFooterHeight =0;
        _tableViewList.estimatedSectionHeaderHeight =0;
         _tableViewList.backgroundColor = [UIColor blackColor];
        _tableViewList.separatorStyle = UITableViewCellSelectionStyleNone;
        [self.view addSubview:_tableViewList];
    }
    return _tableViewList;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat size = [LSZSpecialPackaging initWithReturnsthesizeOf:14 :0.5];
    CGFloat height = [LSZSpecialPackaging caculateHeightOfText:ScreenWidth-100 height:ScreenHeight*8 font:size :self.lyrics];
    if (height+45 < ScreenHeight-ScreenWidth*9/16-50-NAVIGATION_BAR_HEIGHT) {
        return ScreenHeight-ScreenWidth*9/16-50-NAVIGATION_BAR_HEIGHT;
    }else{
        return height+45;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.00000000001;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.00000000001;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UITableViewHeaderFooterView * view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"cell"];
    if (!view) {
        view = [[UITableViewHeaderFooterView alloc]initWithReuseIdentifier:@"cell"];
    }
    view.contentView.backgroundColor = [UIColor blackColor];
    view.backgroundView.backgroundColor = [UIColor blackColor];
    return view;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LSZHeaderBasicInformationHeaderCell * cell = [tableView dequeueReusableCellWithIdentifier:@"LSZHeaderBasicInformationHeaderCell" forIndexPath:indexPath];
    cell.labelTitle.text = self.name;
    CGFloat size = [LSZSpecialPackaging initWithReturnsthesizeOf:14 :0.5];
    CGFloat height = [LSZSpecialPackaging caculateHeightOfText:ScreenWidth-100 height:ScreenHeight*8 font:size :self.lyrics];
    CGRect rect = cell.labelContent.frame;
    rect.origin.y = CGRectGetMaxY(cell.labelTitle.frame)+10;
    rect.size.height = height;
    cell.labelContent.frame = rect;
    cell.labelContent.text = self.lyrics;
    cell.contentView.backgroundColor = [UIColor blackColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
#pragma mark - 奉献支持
-(void)clickButDedication
{
    if ([[_UserM usercode] isEqualToString:@""]) {
        pushAccLoginVC;
    }else{
        Class clz = NSClassFromString(@"LCRmbHtmlVC");
        UIViewController *viewController = [[clz alloc] init];
        [self.navigationController pushViewController:viewController animated:YES];
    }
}
-(NSString *)usingRandomNumbers
{
    NSString * str = [NSString stringWithFormat:@"%ld",(long)arc4random() % 100000];
    return str;
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    self.navigationController.delegate = nil;
    self.player = nil;
}
#pragma mark - UINavigationControllerDelegate 将要显示控制器
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    // 判断要显示的控制器是否是自己
    BOOL isShowHomePage = [viewController isKindOfClass:[self class]];
    [self.navigationController setNavigationBarHidden:isShowHomePage animated:YES];
}
@end
